package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.PartyNotice;
import cn.qidisoft.edu.hzjt.service.zyc.IPartyNoticeService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 管理公示公告
 * 
 * @author zhangwenliang
 * @date 2018.12.15
 */
@Controller
@RequestMapping("/partyNotice/")
public class PartyNoticeController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

	private static String upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }
    private static Map<String, List<PartyNotice>> picMap = new HashMap<>();
    
	@Autowired
	private IPartyNoticeService partyNoticeService;
	
	/**
	 * 跳转到列表页面
	 * 
	 * @return
	 */
	@RequestMapping("list")
	public String list() {
		return "zyc/partyNotice/list";
	}
	/***
	 * 获取列表分页数据
	 * 
	 * @param model
	 * @param request
	 * @param pageSize
	 * @param currentPage
	 * @param student
	 * @return
	 */
	@RequestMapping("getListData")
	@ResponseBody
	public ResponseResult getListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyNotice PartyNotice) {
		System.out.println(pageSize + currentPage);
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "createTime", "desc");
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String subject = request.getParameter("subject");
		if(null != subject) {
			queryMap.put("subject", subject.trim());
		}
		queryMap.put("partyNotice", PartyNotice);
		queryMap.put("orderField", (String) request.getAttribute("orderField"));
		queryMap.put("orderFlag", (String) request.getAttribute("orderFlag"));
		PaginationBean<PartyNotice> paginationBean = partyNoticeService.getListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "add")
	@Token(save = true)
	public String add(ModelMap model, HttpServletRequest request) {
		try {
			 // 获取当前系统用户
            UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            request.setAttribute("user", user);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String today = dateFormat.format(new Date());
            request.setAttribute("createTime", today);
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return "zyc/partyNotice/add";
	}
	/**
	 * 保存公示公告信息
	 * @param model
	 * @param request
	 * @return 3）保存时，对党支部书记和委员，判断是否在党员信息中，没有，则自动加入党员表
	 */
	@RequestMapping(value = "insert")
	public String insert(ModelMap model, HttpServletRequest request, PartyNotice partyNotice,@RequestParam("file") MultipartFile file)throws  Exception {
		try {
			UserEmployee userEmployee =
					(UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String gid = UUID.randomUUID().toString();
			String path = upload;
			String filePath =CommonUtils.createSaveFilePath("JKY_JKS_GSGG", userEmployee.getUserid() );
			if(!file.isEmpty()) {
				// 上传文件路径
				String savePath = path + CommonUtils.fileSeprator + filePath;
				// 上传文件名
				String  filename = file.getOriginalFilename();
				int pos = filename.lastIndexOf(".");
				String lastname = filename.substring(pos, filename.length());
				String name = gid + lastname;
				File filepaths = new File(savePath,name);
				// 判断路径是否存在，如果不存在就创建一个
				if(!filepaths.getParentFile().exists()) {
					filepaths.getParentFile().mkdir();
				}
				// 将上传文件保存到一个目标文件当中
				file.transferTo(new File(savePath + name));
				partyNotice.setImgUrl(filePath + name);

			}
			if(null == partyNotice.getContents()) {
				partyNotice.setContents("");
			}
			partyNotice.setGid(UUIDGenerator.genReqID());
			if(null == partyNotice.getIsImgLink()) {
				partyNotice.setIsImgLink("0");
			}
			// 类别：1-公告 2-新闻 3-通知(默认为1）
			partyNotice.setInfoType(1);
			partyNoticeService.insert(partyNotice);
			String  action = request.getParameter("action");
			if (action.equals("2")) {
				return "redirect:./add";
			}else if(action.equals("1")){
				return "redirect:./view?gGID=" + partyNotice.getgGID();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 跳转到浏览页面
	 * @param request
	 * @return
	 */
	@RequestMapping("view")
	public String view(HttpServletRequest request) {  
		String gGID = request.getParameter("gGID");
		PartyNotice pNotice = new PartyNotice();
		pNotice.setgGID(Integer.parseInt(gGID));
		PartyNotice partyNotice = partyNoticeService.getPartyNotice(pNotice);
		if(null != partyNotice.getCreateTime()) {
			partyNotice.setCreateTime(partyNotice.getCreateTime().substring(0,19));
		}
		if(partyNotice.getOnTop().equals("0")) {
			partyNotice.setOnTop("是");
		} else if(partyNotice.getOnTop().equals("1")) {
			partyNotice.setOnTop("否");
		}
		if(partyNotice.getIssued().equals("0")) {
			partyNotice.setIssued("是");
		} else if(partyNotice.getIssued().equals("1")){
			partyNotice.setIssued("否");
		}
		if(partyNotice.getIsImgLink().equals("0")) {
			partyNotice.setIsImgLink("否");
		} else if(partyNotice.getIsImgLink().equals("1")) {
			partyNotice.setIsImgLink("是");
		}
		String path = upload;
		request.setAttribute("path", path);
		request.setAttribute("partyNotice", partyNotice);
		return "zyc/partyNotice/view";
	}
	/**
	 * 跳转到修改页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "edit")
	@Token(save = true)
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String gGID = request.getParameter("gGID");
			PartyNotice pNotice = new PartyNotice();
			pNotice.setgGID(Integer.parseInt(gGID));
			PartyNotice partyNotice = partyNoticeService.getPartyNotice(pNotice);
			if(null != partyNotice.getCreateTime()) {
				partyNotice.setCreateTime(partyNotice.getCreateTime().substring(0,19));
			}
			String path = upload;
			request.setAttribute("path", path);
			request.setAttribute("partyNotice", partyNotice);
			return "zyc/partyNotice/edit";	
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 修改公示公告信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "update")
	public String update(ModelMap model, HttpServletRequest request, PartyNotice partyNotice, @RequestParam("file") MultipartFile file) throws  Exception{
		try {
			UserEmployee userEmployee =
					(UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String gid = UUID.randomUUID().toString();
			String path = upload;
			String filePath =CommonUtils.createSaveFilePath("JKY_JKS_GSGG", userEmployee.getUserid() );
			if(!file.isEmpty()) {
				// 上传文件路径
				String savePath = path + CommonUtils.fileSeprator + filePath;
				// 上传文件名
				String  filename = file.getOriginalFilename();
				int pos = filename.lastIndexOf(".");
				String lastname = filename.substring(pos, filename.length());
				String name = gid + lastname;
				File filepaths = new File(savePath,name);
				// 判断路径是否存在，如果不存在就创建一个
				if(!filepaths.getParentFile().exists()) {
					filepaths.getParentFile().mkdir();
				}
				// 将上传文件保存到一个目标文件当中
				file.transferTo(new File(savePath + name));
				partyNotice.setImgUrl(filePath + name);

			}
			// 更新信息
			if(null == partyNotice.getIsImgLink()) {
				partyNotice.setIsImgLink("0");
				partyNotice.setImgUrl("");
			}
			partyNoticeService.update(partyNotice);
			String  action = request.getParameter("action");
			if (action.equals("2")) {
				return "redirect:./add";
			}else if(action.equals("1")){
				return "redirect:./view?gGID=" + partyNotice.getgGID();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 删除公示公告信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			 String[] idList = request.getParameter("idList").split(",");
             PartyNotice data = new PartyNotice();
             data.setIds(idList);
			partyNoticeService.delete(data);
			
			return "redirect:list";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}
	/**
	 * 公示公告下载
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_partyNotice")
	public @ResponseBody void export_partyNotice(HttpServletRequest request, HttpServletResponse response,PartyNotice partyNotice) throws Exception {
		try {
			PartyNotice pNotice = new PartyNotice();
			Map<String, Object> queryMap = new HashMap<String, Object>();
			String subject = request.getParameter("subject");
			if(null != subject) {
				queryMap.put("subject", subject.trim());
			}
			queryMap.put("partyNotice", partyNotice);
			List<PartyNotice> datalist = partyNoticeService.getPartyNoticeList(queryMap);
			String[][] title_name = { { "id", "标题", "是否置顶", "是否发布", "是否图片链接","创建人","创建时间"} };
			String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18", "st_12_n_20", "st_12_n_20",
					"st_12_n_20" ,"st_12_n_20" };
			String fileName = "公示公告";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyNotice res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					if(null != res.getCreateTime()) {
						res.setCreateTime(res.getCreateTime().substring(0, 19));
					}
					if(res.getOnTop().equals("0")) {
						res.setOnTop("是");
					} else if(res.getOnTop().equals("1")) {
						res.setOnTop("否");
					}
					if(res.getIssued().equals("0")) {
						res.setIssued("是");
					} else if(res.getIssued().equals("1")) {
						res.setIssued("否");
					}
					if(res.getIsImgLink().equals("0")) {
						res.setIsImgLink("否");
					} else if(res.getIsImgLink().equals("1")) {
						res.setIsImgLink("是");
					}
					map.put("gGID", res.getgGID());
					map.put("subject", res.getSubject());
					map.put("onTop", res.getOnTop());
					map.put("issued", res.getIssued());
					map.put("isImgLink", res.getIsImgLink());
					map.put("creatorName", res.getCreatorName());
					map.put("createTime", res.getCreateTime());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "公示公告";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
	 /**
     * 上传
     *
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {
        List<PartyNotice> list = new ArrayList<PartyNotice>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<PartyNotice> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;
        //path = request.getServletContext().getRealPath("/") +"img";
        try {
            String gid = UUID.randomUUID().toString();
            String name = file.getOriginalFilename();// 获取上传文件名
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            PartyNotice docFile = new PartyNotice();
            String filePath =CommonUtils.createSaveFilePath("JKY_JKS_GSGG", userEmployee.getUserid() );
            if (!file.isEmpty()) {
                /**
                 * 2018.12.10
                 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
                 */
            	  docFile.setGid(gid);
                  docFile.setMufile(file);
                  docFile.setInputStream(file.getInputStream());
                  docFile.setImgUrl(filePath + gid +"."+ name);
				  docFile.setSysfilepath(path + CommonUtils.fileSeprator + filePath +gid +"."+ name);
                if (docFileResourceList != null && docFileResourceList.size() > 0) {
                    docFileResourceList.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
                } else {
                    list.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), list);
                }
                LOGGER.info("附件上传成功！");
            }
            PrintWriter writer = null;
            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getImgUrl());
            // 文件名称
            docFile2.setFilename(name);
            docFile2.setSysfilepath(path + CommonUtils.fileSeprator + filePath + name);
            writer = response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	@RequestMapping(value="/getNotice")
	@ResponseBody
	public List<PartyNotice> getNotice() {
		List<PartyNotice> pList =  partyNoticeService.getpartyNoticeEight();
		return pList;
	}
	
	@RequestMapping(value="/getByGgId")
	@ResponseBody
	public PartyNotice getByGgId() {
		Integer gGid = 6;
		PartyNotice partyNotice = partyNoticeService.getByGgId(gGid);
		return partyNotice;
	}
}
